<template>
  <div class="table-container">

    <div class="select-container">
      <el-select
        v-model="selectedFilter"
        placeholder="请选择药品"
        @change="handleFilterChange"
        filterable
        clearable
        style="width: 300px;"
      >
        <el-option
          v-for="item in medications"
          :key="item.drugId"
          :label="item.name"
          :value="item.name"
        ></el-option>
      </el-select>
  
      <el-table :data="paginatedTableData" border stripe style="margin-top: 20px">
        <el-table-column prop="drugId" label="药品编号" width="100" />
        <el-table-column prop="name" label="药品名称" />
        <el-table-column prop="number" label="库存" />
      </el-table>
    </div>
    
    <el-card v-if="drugs != ''" 
      class="card-container" style="width: 300px;">
      <template #header>
        <div class="card-header">
          <span style="font-weight: bold; color: #909399;">配药单</span>
        </div>
      </template>
      <div v-html="formattedDrugs" style="font-size: 14px; color: #606266;"></div>    </el-card>
  </div>
  <div class="pagination-block">
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="displayedData.length"
    />
  </div>
</template>
 
<script>
import request from "@/utils/request.js";

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 9,
      // 原始数据
      medications: [
        // {drugId: '1659', name: '氟康唑乳膏', price: 95.3, number: 20},
        // {drugId: '1374', name: '福治芬注射液', price: 87.25, number: 10},
        // {drugId: '2876', name: '溴氯噻吨滴眼液', price: 39.99, number: 0}
      ],
      // 当前选择的筛选条件
      selectedFilter: '',
      // 当前显示在表格中的数据（累积的）
      displayedData: [],
      // 用于记录已经添加到displayedData中的药品id，以确保去重
      addedMedicineIds: new Set(),
      drugs: '', // 从路由中获取的值
      // 标记是否为第一次点击搜索框
      isFirstFilterClick: true,
    };
  },
  computed: {
    formattedDrugs() {
      // 将换行符替换为 <br> 标签
      return this.drugs.replace(/\n/g, '<br>');
    },
    paginatedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.displayedData.slice(start, end);
    },
  },
  methods: {
    requestDrugs() {
      request
        .get("/drug/getAllDrug")
        .then((res) => {
            this.medications = res.data;
            this.displayedData = res.data;
            console.log('返回的药品:', res.data);
        })
        .catch((error) => {
            // 处理请求错误
            console.error('请求出错:', error);
        });
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      console.log("当前页码:", this.currentPage);
    },
    handleFilterChange(filter) {
      // 如果是第一次点击搜索框，则重置数据
      if (this.isFirstFilterClick) {
        this.displayedData = [];
        this.addedMedicineIds.clear();
        this.isFirstFilterClick = false; // 设置为 false，表示已进行过第一次点击
      }
      const newData = this.medications
        .filter(item => item.name.includes(filter) && !this.addedMedicineIds.has(item.drugId))
        .map(item => {
          this.addedMedicineIds.add(item.drugId);
          return item;
        });
      this.displayedData = [...this.displayedData, ...newData];
    },
  },
  mounted() {
    this.requestDrugs(); // 在组件挂载后立即查询药品数据
  },
  created() {
    if (this.$route.params.drugs != '-1') {
      // 在组件创建时从路由参数中获取药品 ID
      this.drugs = this.$route.params.drugs;
    }
  },
};
</script>
 
<style scoped>
.table-container {
  height: 65vh;
  display: flex;
  gap: 20px; /* 添加间距 */
  width: 100%;
}
.card-container {
  width: 300px;
  margin-right: auto;
}
.select-container {
  flex: 1;
}
.pagination-block {
  display: flex; /* 使用flexbox布局 */
  justify-content: center; /* 水平居中对齐 */
  margin-top: 20px; /* 添加上边距 */
}
.pagination-block el-pagination {
  justify-content: center;
}
</style>